package com.wm.blog_config.config;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 半卷流年
 * @date 2020-5-7 12:30
 */
@Component
@ServerEndpoint("/socket")//标记此类为服务端
@Slf4j
public class WebSocketServerConfig {
    /**
     * 存放所有在线的客户端
     */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    @OnClose
    public void onClose(Session session) {
        //从map中移除
        clients.remove(session.getId());
    }

    @OnOpen
    public void onOpen(Session session) {
        //存放到map
        clients.put(session.getId(),session);
        log.info("欢迎id={}你的加入成功" , session.getId());
    }

    public void sendMessage(String sessionId,String string){
        try {
            clients.get(sessionId).getBasicRemote().sendText(JSONObject.toJSONString(string));
        } catch (IOException e) {
            log.error("消息推送异常,sessionId:[{}],发送的消息:[{}]",sessionId,string);
        }
    }

    /**
     * 消息群发
     * @param str
     * @throws IOException
     */
    public void sendMessageToAll(String str)  {
        clients.forEach((k,v) -> {
                this.sendMessage(k,str);
        });
    }
}
